'use strict'

import {app, protocol, BrowserWindow, ipcMain, dialog, shell, session, Notification} from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
import path from "path";
import fs from "fs";
const isDevelopment = process.env.NODE_ENV !== 'production'

let cacheDownItem = {}

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

async function createWindow() {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 1300,
    height: 720,
    icon: path.resolve(__dirname, "./icon/logo.png"),
    frame:false,
    webPreferences: {
      webSecurity:false, //禁用同源策略（设置跨域）
      nodeIntegration:true,//启动 node
      contextIsolation:false,// 上下文隔离
      webviewTag:true //  是否启用<webview>浏览器标签
    }
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }


// 最小化
  ipcMain.on("min", function () {
    win.minimize()
  })

  // 最大化
  ipcMain.on("max", function () {
    if (win.isMaximized()) {
      win.unmaximize()
    } else {
      win.maximize()
    }
  })

  // 关闭程序
  ipcMain.on("close", function () {
    win.close();
  })


  // 设置下载路径
  ipcMain.on("set_path", function (e, data = {}) {
    let { path } = data
    if (path) {
      if (path !== 'not') app.setPath('downloads', path);
      e.reply('set_path', app.getPath('downloads'));
    } else {
      dialog.showOpenDialog({
        title: '选择下载目录',
        defaultPath: app.getPath('downloads'),
        properties: ['openDirectory']
      }).then((files) => {
        if (!files.canceled) {// 如果有选中
          app.setPath('downloads', files.filePaths[0])
        }
        e.reply('set_path', files)
      })
    }
  })

  // 设置下载路径
  ipcMain.on("check_path", function (e, data = {}) {
    let { path } = data
    fs.access(path, fs.constants.F_OK, (err) => {
      if (!err) {
        shell.showItemInFolder(path)
      }
      e.reply('check_path' + path, err);
    });
  })

  // 下载
  ipcMain.on("down-file", function (e, data) {
    let { url } = data
    if (!cacheDownItem[url]) {
      cacheDownItem[url] = { ...data }
      downfile(url)
    } else {
      /*   e.sender("down-file", "文件正在下载") */
    }
  })

  // 下载文件
  const downfile = (url) => {
    session.defaultSession.downloadURL(url)
  }


  // 监听下载
  session.defaultSession.on('will-download', (e, item) => {
    try {

      const url = item.getURL()
      let cacheItem = cacheDownItem[url] || {
        notSend: true
      };
      // 获取文件的总大小
      const totalBytes = item.getTotalBytes();
      // 设置下载路径
      const filePath = path.join(app.getPath("downloads"), item.getFilename());
      item.setSavePath(filePath);

      // 缓存downitem
      cacheItem._downFileItem = item;
      cacheItem.path = item.getSavePath();
      cacheItem.eTag = item.getETag();
      cacheItem.urlChain = item.getURLChain();
      cacheItem.length = totalBytes
      cacheItem.lastModified = item.getLastModifiedTime()
      cacheItem.startTime = item.getStartTime();

      let lastBytes = 0;

      // 监听下载过程，计算并设置进度条进度
      item.on('updated', (event, state) => {
        if (state === 'interrupted') {
          cacheItem.state = 'interrupted'
        } else if (state === 'progressing') {
          if (item.isPaused()) {
            cacheItem.state = 'paused'
          } else {
            let offset = item.getReceivedBytes();
            cacheItem.state = 'downing';
            cacheItem.speedBytes = offset - lastBytes;
            cacheItem.progress = parseInt((offset / totalBytes) * 100);
            cacheItem.offset = offset
            lastBytes = offset
          }
        }
        !cacheItem.notSend && win.webContents.send("update-down-state", JSON.parse(JSON.stringify(cacheItem)));
      })

      // 下载完成
      item.once('done', (event, state) => {
        cacheItem.done = 'end'
        switch (state) {
          case 'interrupted':
            cacheItem.state = 'interrupted-err'
            break;
          case 'cancelle':
            cacheItem.state = 'cancelle'
            break;
          default:
            cacheItem.state = 'completed'
            notification(cacheItem.path)
            break;
        }

        !cacheItem.notSend && win.webContents.send("update-down-state", JSON.parse(JSON.stringify(cacheItem)))

        //删除缓存
        delete cacheDownItem[url]
        cacheItem = null;
        item = null;
      })

      // 恢复
      if (item.canResume) {
        item.resume()
      }

    } catch (error) {
      console.log(error)
    }
  })


  let noti
  const notification = (url) => {
    noti = new Notification({
      title: "下载成功",
      bodyString: url,
      silentBoolean: false,
      icon: url
    })
    noti.show()
    noti.once("click", () => {
      shell.showItemInFolder(url)
    })
  }


}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  /*if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      await installExtension(VUEJS_DEVTOOLS)
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString())
    }
  }*/
  createWindow()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}
